package tongwentongshu.com.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.huawei.android.pushagent.PushManager;
import com.mob.MobApplication;
import com.tencent.imsdk.TIMGroupReceiveMessageOpt;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushListener;
import com.tencent.imsdk.TIMOfflinePushNotification;
import com.tencent.imsdk.TIMOfflinePushSettings;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.qalsdk.sdk.MsfSdkUtils;

import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import de.greenrobot.event.EventBus;

import tongwentongshu.com.app.bean.MessageEvent;
import tongwentongshu.com.app.utils.PushUtil;
import tongwentongshu.com.app.utils.ToastUtil;


/**
 * Created by XiongBin on 2017/6/26.
 */

public class App extends MobApplication {
    //位置页面code
    public static final int SelectLocationCode = 13;
    //扫码页面code
    public static final int CaptureCode = 14;
    public static final String NAME = "name";
    public static final String CODE = "code";
    public static final String POINT = "point";
    // 获取到主线程的上下文
    public static App mContext;
    public static Context context;
    private List<Activity> mallActivityList = new LinkedList<Activity>();//个人中心流程
    private List<Activity> readActivityList = new LinkedList<Activity>();//再次分享流程
    public static Map<String, String> PushMessage = null;// 友盟推送信息

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        context = getApplicationContext();


        //初始化imsdk
        if (MsfSdkUtils.isMainProcess(this)) {

            //初始化SDK基本配置
            TIMSdkConfig config = new TIMSdkConfig(1400036219)
                    .enableCrashReport(false)
                    .enableLogPrint(true)
                    .setLogLevel(TIMLogLevel.DEBUG)
                    .setLogPath(Environment.getExternalStorageDirectory().getPath() + "/justfortest/");

            //初始化SDK
            TIMManager.getInstance().init(getApplicationContext(), config);
            TIMManager.getInstance().setOfflinePushListener(new TIMOfflinePushListener() {
                @Override
                public void handleNotification(TIMOfflinePushNotification notification) {
                    if (notification.getGroupReceiveMsgOpt() == TIMGroupReceiveMessageOpt.ReceiveAndNotify) {
                        //消息被设置为需要提醒
                        notification.doNotify(getApplicationContext(), R.mipmap.tongwentongshu);
                    }
                }
            });

            //检测是否初始化并集成成功
            Log.e("LiveApplication", TIMManager.getInstance().getVersion());
            registerPush();

        }


        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.d("log", "友盟ID：" + deviceToken);
                PushAgent.getInstance(mContext).setMessageHandler(mUmengMessageHandler);
                PushAgent.getInstance(mContext).setNotificationClickHandler(notificationClickHandler);
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });
    }


    public void registerPush() {
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        com.tencent.qcloud.presentation.event.MessageEvent.getInstance();


        TIMOfflinePushSettings settings = new TIMOfflinePushSettings();
//开启离线推送
        settings.setEnabled(true);
//设置收到C2C离线消息时的提示声音，这里把声音文件放到了res/raw文件夹下
        settings.setC2cMsgRemindSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.dudulu));
//设置收到群离线消息时的提示声音，这里把声音文件放到了res/raw文件夹下
        settings.setGroupMsgRemindSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.dudulu));

        TIMManager.getInstance().setOfflinePushSettings(settings);


        String vendor = Build.MANUFACTURER;
        Log.e("vendor", vendor.toLowerCase(Locale.ENGLISH));
        if (vendor.toLowerCase(Locale.ENGLISH).contains("xiaomi") && shouldMiInit()) {
            Log.e("小米", "registerPush");
            //注册小米推送服务
            MiPushClient.registerPush(mContext.getApplicationContext(), "2882303761517604448", "5311760450448");
        } else if (vendor.toLowerCase(Locale.ENGLISH).contains("huawei")) {
            //请求华为推送设备token
            PushManager.requestToken(this);
        }
    }

    /**
     * 判断小米推送是否已经初始化
     */
    private boolean shouldMiInit() {
        ActivityManager am = ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = mContext.getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static Context getContext() {
        return context;
    }

    public static App getApplication() {
        return mContext;
    }

    public void addMallActivity(Activity activity) {
        mallActivityList.add(activity);
    }

    public void addReadingActivity(Activity activity) {
        readActivityList.add(activity);
    }

    public void exitMall() {
        if (mallActivityList != null) {
            Activity activity;
            for (int i = 0; i < mallActivityList.size(); i++) {
                activity = mallActivityList.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }

                    activity = null;
                }
                mallActivityList.remove(i);
                i--;
            }
        }
    }

    public void exitRead() {
        if (readActivityList != null) {
            Activity activity;
            for (int i = 0; i < readActivityList.size(); i++) {
                activity = readActivityList.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }

                    activity = null;
                }
                readActivityList.remove(i);
                i--;
            }
        }
    }

    /**
     * 友盟消息接收
     */
    UmengMessageHandler mUmengMessageHandler = new UmengMessageHandler() {
        @Override
        public Notification getNotification(Context arg0, UMessage arg1) {
            // TODO Auto-generated method stub
            if (arg1.extra != null) {
//                ToastUtil.show(mContext, "接收到了");
//                Intent intent0 = new Intent("com.SystemMessage_Fragment.receiver");
//                intent0.putExtra("Umpush", true);
//                mContext.sendBroadcast(intent0);
//
//                Intent intent2 = new Intent("com.PersonalActivity.receiver");
//                intent2.putExtra("Umpush", true);ll
//                mContext.sendBroadcast(intent2);
//
//                Intent intent3 = new Intent("com.MainActivity.receiver");
//                intent3.putExtra("DotView", true);
//                mContext.sendBroadcast(intent3);
            }

            if (isAppOnForeground(mContext)) {
//                PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
//                Intent intent = new Intent("com.BaseActivity.receiver");
//                intent.putExtra("isPushToast", true);
//                if (arg1.extra != null) {
//                    if ("0".equals(arg1.extra.get("messtype"))) {
//                        intent.putExtra("PushToast", "您有一个新的系统消息，请去查看！");
//                    } else if ("1".equals(arg1.extra.get("messtype"))) {
//                        intent.putExtra("PushToast", "您有一个新的回复消息，请去查看！");
//                    } else if ("11".equals(arg1.extra.get("messtype"))) {
//                        intent.putExtra("PushToast", "您有一个新的专场提醒，请去查看！");
//                    } else {
//                        intent.putExtra("PushToast", "您有一个推送消息，请去查看！");
//                    }
//                } else {
//                    intent.putExtra("PushToast", "您有一个推送消息，请去查看！");
//                }
//                mContext.sendBroadcast(intent);
            } else {
                PushAgent.getInstance(mContext).setNotificaitonOnForeground(true);
            }
            return super.getNotification(arg0, arg1);
        }
    };

    // 在进程中去寻找当前APP的信息，判断是否在前台运行
    public static boolean isAppOnForeground(Context mContext) {
        ActivityManager activityManager = (ActivityManager) mContext
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = mContext.getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 友盟通知栏点击事件
     * {messtype=2, messid=381, messurl=http://tongwentongshu.cn/index.php?g=&m=User&a=notice_message&id=381&type=2, youmeng=yes}
     */
    UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
        @Override
        public void dealWithCustomAction(Context context, UMessage msg) {
            Log.d("log", "友盟通知栏：" + msg.extra.toString());
            // 判断系统消息 1为评论回复消息，0为系统消息
//            MainActivity.PushMessage = msg.extra;
            //目前都是当前APP在前台时是文字提醒所有直接启动APP
            // 判断App是否已经启动
            String book_id = msg.extra.get("book_id");
            String messurl = msg.extra.get("messurl");
            String messid = msg.extra.get("messid");
            String message_style = msg.extra.get("message_style");
            String is_auth = msg.extra.get("is_auth");
            if (APPIsRun("tongwentongshu.com.app")) {
                if (isAppOnForeground(mContext)) {

                    EventBus.getDefault().post(new MessageEvent(book_id, messurl, messid, message_style, is_auth));

//                    // 判断当前APP不再前台
//                    Intent i = new Intent(mContext, WebViewActivity.class);
//                    i.putExtra("url", messid);
//                    startActivity(i);
//                    mContext.startActivity(i);
                } else {
                    Intent mainIntent = new Intent(context, MapMainActivity.class);
                    //将MainAtivity的launchMode设置成SingleTask, 或者在下面flag中加上Intent.FLAG_CLEAR_TOP,
                    //如果Task栈中有MainActivity的实例，就会把它移到栈顶，把在它之上的Activity都清理出栈，
                    //如果Task栈不存在MainActivity实例，则在栈顶创建
                    mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    EventBus.getDefault().post(new MessageEvent(book_id, messurl, messid, message_style, is_auth));
//                    EventBus.getDefault().post(new UrlEvent(msg.extra.get("messurl")));
                }
            } else {
                Bundle args = new Bundle();
                args.putString("book_id", book_id);
                args.putString("messurl", messurl);
                args.putString("messid", messid);
                args.putString("message_style", message_style);
                args.putString("is_auth", is_auth);
                startAPP(mContext, "tongwentongshu.com.app", args);
            }
        }
    };

    /**
     * 携带数据页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        mContext.startActivity(intent);
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        mContext.startActivity(new Intent(mContext, clz));
    }


    /**
     * 判断APP是否运行
     *
     * @param MY_PKG_NAME
     * @return
     */
    private boolean APPIsRun(String MY_PKG_NAME) {

        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(MY_PKG_NAME)
                    || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
                isAppRunning = true;
                Log.d("log", info.topActivity.getPackageName()
                        + " info.baseActivity.getPackageName()="
                        + info.baseActivity.getPackageName());
                break;
            }
        }
        return isAppRunning;
    }

    static String EXTRA_BUNDLE = "intent_";

    /*
     * 启动一个app
     */
    public static void startAPP(Context mContext, String appPackageName, Bundle args) {
        try {
            Intent intent = mContext.getPackageManager()
                    .getLaunchIntentForPackage(appPackageName);
            intent.setFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            intent.putExtra(EXTRA_BUNDLE, args);
            mContext.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.show(mContext, "该程序没有安装");
        }
    }


}
